package com.shqcjd.sinopecdemomobile.ui.activity.maintain;

import android.content.Context;
import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Spinner;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.Gson;
import com.shqcjd.sinopecdemomobile.R;
import com.shqcjd.sinopecdemomobile.api.ApiService;
import com.shqcjd.sinopecdemomobile.app.AppConstant;
import com.shqcjd.sinopecdemomobile.app.MyApp;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxObserver;
import com.shqcjd.sinopecdemomobile.helper.rxjavahelper.RxSchedulersHelper;
import com.shqcjd.sinopecdemomobile.model.ResponseData;
import com.shqcjd.sinopecdemomobile.model.eventbus.RefreshData;
import com.shqcjd.sinopecdemomobile.model.pojo.AppOperationGuideMode;
import com.shqcjd.sinopecdemomobile.model.pojo.QRScanBean;
import com.shqcjd.sinopecdemomobile.model.pojo.RouteQueryBean;
import com.shqcjd.sinopecdemomobile.ui.activity.FileListActivity;
import com.shqcjd.sinopecdemomobile.ui.activity.GenerateQRcodeActivity;
import com.shqcjd.sinopecdemomobile.ui.adapter.MaintainListAdapter;
import com.shqcjd.sinopecdemomobile.ui.adapter.RouteSpinnerAdapter;
import com.shqcjd.sinopecdemomobile.ui.base.BaseActivity;
import com.shqcjd.sinopecdemomobile.ui.base.BasePresenter;
import com.shqcjd.sinopecdemomobile.util.Config;
import com.shqcjd.sinopecdemomobile.util.PrefUtils;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import io.reactivex.disposables.Disposable;

/**
 * 操作向导列表
 */
public class MaintainListActivity extends BaseActivity {
    @BindView(R.id.rv_tip_wizard_list)
    RecyclerView rv_tip_wizard_list;
    @BindView(R.id.iv_toolbar_back)
    ImageView ivToolbarBack;
    @BindView(R.id.tv_toolbar_center)
    TextView tvToolbarCenter;
    @BindView(R.id.ll_search)
    LinearLayout llSearch;
    @BindView(R.id.et_search)
    EditText editText;
    @BindView(R.id.rl_isnull)
    RelativeLayout rlIsnull;
    @BindView(R.id.sr_inspection)
    SwipeRefreshLayout srInspection;
    @BindView(R.id.filter_btn)
    View filterSelect;
    @BindView(R.id.rl_pop)
    RelativeLayout rlPop;
    private View contentView;
    private String strSearch;
    private int page = 1;
    private int isRefreshOrLoadMore = 0;//0代表刷新  1代表加载更多

    private List<AppOperationGuideMode.ItemsBean> adapterList = new ArrayList<>();

    private int total;
    private MaintainListAdapter maintainListActivity;


    private RouteSpinnerAdapter locationAdapter;//片区适配器
    private RouteSpinnerAdapter companyAdapter;//集团适配器
    private RouteSpinnerAdapter factoryAdapter;//工厂适配器
    private RouteSpinnerAdapter childAdapter;//分厂适配器
    private List<RouteQueryBean> locationList = new ArrayList<>();
    private List<RouteQueryBean> childList = new ArrayList<>();
    private List<RouteQueryBean> companyList = new ArrayList<>();
    private List<RouteQueryBean> factoryList = new ArrayList<>();

    private Context context;
    private String area = "";//片区
    private String branch_factory = "";//分厂
    private String factory = "";//厂
    private String group = "";//集团编号

    @Override
    protected BasePresenter createPresenter() {
        return null;
    }

    @Override
    protected int provideContentViewId() {
        return R.layout.activity_tip_wizard_list;
    }

    @Override
    public void initView() {
        EventBus.getDefault().register(this);
        context = this;
        tvToolbarCenter.setText("智能维修");
        maintainListActivity = new MaintainListAdapter();
        rv_tip_wizard_list.setLayoutManager(new LinearLayoutManager(this){
            @Override
            public void onLayoutChildren(RecyclerView.Recycler recycler, RecyclerView.State state) {
                try {
                    //try catch一下
                    super.onLayoutChildren( recycler, state );
                } catch (IndexOutOfBoundsException e) {

                }

            }
        });
        filterSelect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showPopupWindow(rlPop);
            }
        });
        rv_tip_wizard_list.setAdapter(maintainListActivity);
        ivToolbarBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        editText.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                strSearch = editable.toString();
                refreshData();
            }
        });
        maintainListActivity.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {

            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                AppOperationGuideMode.ItemsBean node = adapterList.get(position);
                Intent intent;
                switch (view.getId()) {
                    case R.id.tv_start_btn://开始操作
//                        preShowProgressDialog(position);
                        intent = new Intent(MaintainListActivity.this, MaintainDetailActivity.class);
                        intent.putExtra("data",node);
                        startActivity(intent);
                        break;
                    case R.id.fl_generate_btn://生成二维码

                        showGenerateDialog(position);
                        break;
                    case R.id.tv_file_btn://文件列表
                        intent = new Intent(MaintainListActivity.this, FileListActivity.class);
                        intent.putExtra("taskId", node.workTaskId);
                        startActivity(intent);
                        break;
                }
            }
        });

        maintainListActivity.setNewData(adapterList);

        maintainListActivity.setOnLoadMoreListener(new BaseQuickAdapter.RequestLoadMoreListener() {
            @Override
            public void onLoadMoreRequested() {
                int pageSize = total % Config.PAGE_TOTAL == 0 ? total / Config.PAGE_TOTAL : total / Config.PAGE_TOTAL + 1;
                if (page >= pageSize||maintainListActivity.getData().size()<Config.PAGE_TOTAL) {
                    rv_tip_wizard_list.post(new Runnable() {
                        @Override
                        public void run() {
                            maintainListActivity.loadMoreEnd();
                        }
                    });
                } else {
                    loadMoreData();
                }
            }
        });

        srInspection.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
            @Override
            public void onRefresh() {
                refreshData();
            }
        });
        getQueryLocationBean("area");
        refreshData();

    }



    private void showPopupWindow(ViewGroup view) {
        if(contentView!=null){
            contentView.setVisibility(View.VISIBLE);
            return;
        }
        contentView = LayoutInflater.from(view.getContext()).inflate(
                R.layout.pop_window, view, false);
        view.addView(contentView);

        RelativeLayout rl = contentView.findViewById(R.id.rl);
        LinearLayout ll_pop_content = contentView.findViewById(R.id.ll_pop_content);
        Spinner sp_pop_location = contentView.findViewById(R.id.sp_pop_location);
        Spinner sp_pop_child = contentView.findViewById(R.id.sp_pop_child);
        Spinner sp_pop_company = contentView.findViewById(R.id.sp_pop_company);
        Spinner sp_pop_factory = contentView.findViewById(R.id.sp_pop_factory);
        Button btn_pop_reset = contentView.findViewById(R.id.btn_pop_reset);
        Button btn_pop_commit = contentView.findViewById(R.id.btn_pop_commit);

        rl.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                contentView.setVisibility(View.GONE);
            }
        });
        ll_pop_content.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                return true;
            }
        });

        //重置
        btn_pop_reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                companyList.clear();
                factoryList.clear();
                childList.clear();
                locationAdapter.notifyDataSetChanged();
                companyAdapter.notifyDataSetChanged();
                factoryAdapter.notifyDataSetChanged();
                childAdapter.notifyDataSetChanged();
                sp_pop_location.setSelection(0);
            }
        });

        //确定
        btn_pop_commit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                area = (locationList==null||locationList.isEmpty())?"":locationList.get(sp_pop_location.getSelectedItemPosition()).code;
                group = (companyList==null||companyList.isEmpty())?"":companyList.get(sp_pop_company.getSelectedItemPosition()).code;
                factory = (factoryList==null||factoryList.isEmpty())?"":factoryList.get(sp_pop_factory.getSelectedItemPosition()).code;
                branch_factory = (childList==null||childList.isEmpty())?"":childList.get(sp_pop_child.getSelectedItemPosition()).code;
                refreshData();
                contentView.setVisibility(View.GONE);
            }
        });


        sp_pop_location.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                if (locationList.get(position).code.isEmpty()) {
                    return;
                }
                getQueryCompanynBean(locationList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_company.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryFactoryBean(companyList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_factory.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                getQueryChildBean(factoryList.get(position).code);
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        sp_pop_child.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        locationAdapter = new RouteSpinnerAdapter(context, locationList);
        childAdapter = new RouteSpinnerAdapter(context, childList);
        companyAdapter = new RouteSpinnerAdapter(context, companyList);
        factoryAdapter = new RouteSpinnerAdapter(context, factoryList);
        sp_pop_location.setAdapter(locationAdapter);
        sp_pop_company.setAdapter(companyAdapter);
        sp_pop_factory.setAdapter(factoryAdapter);
        sp_pop_child.setAdapter(childAdapter);
    }

    private void getQueryCompanynBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            companyList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryFactoryBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            factoryList.clear();
                            childList.clear();
                            factoryList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }

    private void getQueryChildBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            childList.clear();
                            childList.add(new RouteQueryBean("", "", "全部"));
                            childList.addAll(retData.data);
                            locationAdapter.notifyDataSetChanged();
                            companyAdapter.notifyDataSetChanged();
                            factoryAdapter.notifyDataSetChanged();
                            childAdapter.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }



    private void refreshData() {
        refreshOrLoadMore();
        srInspection.setRefreshing(true);
        isRefreshOrLoadMore = 0;
        page = 1;
        adapterList.clear();
        getData(page);
    }

    private void loadMoreData() {
        isRefreshOrLoadMore = 1;
        getData(page + 1);
    }

    private void refreshOrLoadMore() {
        if (maintainListActivity != null) {
            maintainListActivity.notifyLoadMoreToLoading();
        }
    }


    private void getData(int p){
        String keyWord = strSearch==null?"":strSearch;
        Map<String, String> map = new HashMap<>();
        map.put("pageIndex", p + "");
        map.put("pageSize", Config.PAGE_TOTAL + "");
        map.put("area", area);
        map.put("branchFactory", branch_factory);
        map.put("equipmentTypeName", keyWord);
        map.put("factory", factory);
        map.put("group", group);
        ApiService.getRepairTaskListHttp(new JSONObject(map))
                .compose(RxSchedulersHelper.io_main())
                .safeSubscribe(new RxObserver<ResponseData<AppOperationGuideMode>>() {
                    @Override
                    public void _onNext(ResponseData<AppOperationGuideMode> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {

                            total = retData.data.total;
                            adapterList.addAll(retData.data.items);

                            if (isRefreshOrLoadMore == 1) {
                                page = page + 1;
                                maintainListActivity.loadMoreComplete();
                            }
                            if(adapterList.size()==0){
                                rlIsnull.setVisibility(View.VISIBLE);
                            }else{
                                rlIsnull.setVisibility(View.INVISIBLE);
                            }
                            maintainListActivity.notifyDataSetChanged();
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {

                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        srInspection.setRefreshing(false);
                    }
                });


    }




    /**
     * 显示操作进度
     */
    /*private void preShowProgressDialog(int position){
        showWaitingDialog("正在获取数据");
        ApiService.getGuideTree(adapterList.get(position).workTaskId)
                .compose(RxSchedulersHelper.io_main())
                .safeSubscribe(new RxObserver<ResponseData<ArrayList<TreeNode>>>() {
                    @Override
                    public void _onNext(ResponseData<ArrayList<TreeNode>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            ArrayList<TreeNode> backList = new ArrayList<>();
                            treeToList(retData.data,backList);
                            AppOperationGuideMode.ItemsBean node = adapterList.get(position);
                            showProgressDialog(backList,node.currentStepId,node.workTaskId,node.guideType,node.equipmentTypeId);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                        hideWaitingDialog();
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                        hideWaitingDialog();

                    }
                });

    }
    private void showProgressDialog(ArrayList<TreeNode> backList,int currentStepId,int taskId,String guideType,int equipmentTypeId){
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(R.layout.custome_tip_wizard_progress, false)
                .show();
        View customView = dialog.getCustomView();
        RecyclerView rv_progress = customView.findViewById(R.id.rv_progress);
        TipWizardProgressAdapter tipWizardProgressAdapter = new TipWizardProgressAdapter(currentStepId);
        rv_progress.setLayoutManager(new LinearLayoutManager(this));
        rv_progress.setAdapter(tipWizardProgressAdapter);
        tipWizardProgressAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter adapter, View view, int position) {
                TreeNode node = backList.get(position);
                Intent intent = new Intent(MaintainListActivity.this, MaintainDetailActivity.class);
                intent.putExtra("taskId",taskId);
                intent.putExtra("stepIndexId",node.current.id);
                intent.putExtra("guideType",guideType);
                intent.putExtra("equipmentTypeId",equipmentTypeId);
                startActivity(intent);
                dialog.dismiss();
            }
        });
        tipWizardProgressAdapter.setNewData(backList);

    }

    private void treeToList(ArrayList<TreeNode> paraList,ArrayList<TreeNode> backList){
        for (TreeNode node:paraList){
            backList.add(node);
            if (node.children!=null){
                treeToList(node.children,backList);
            }
        }

    }*/

    /**
     * 生成二维码
     */
    private void showGenerateDialog(int index){
        Gson gson = new Gson();
        AppOperationGuideMode.ItemsBean node =  adapterList.get(index);
        QRScanBean bean = new QRScanBean();
        bean.token = PrefUtils.getString(MyApp.getmContext(), AppConstant.TOKEN_KEY, "-1");
        bean.json = gson.toJson(node.getGuideQR());
        bean.sceneType =2;
        String json = gson.toJson(bean);

        Intent intent = new Intent(context, GenerateQRcodeActivity.class);
        intent.putExtra("QRcode",json);
        startActivity(intent);

//        new AsyncTask<Void, Void, Bitmap>() {
//            @Override
//            protected Bitmap doInBackground(Void... params) {
//                return QRCodeEncoder.syncEncodeQRCode(json, BGAQRCodeUtil.dp2px(MaintainListActivity.this, 150));
//            }
//
//            @Override
//            protected void onPostExecute(Bitmap bitmap) {
//                if (bitmap != null) {
//                    Dialog dialog = new Dialog(MaintainListActivity.this);
//                    dialog.setContentView(R.layout.custome_generate_qrcode);
//                    dialog.show();
//                    Window dialogWindow = dialog.getWindow();
//                    WindowManager m = MaintainListActivity.this.getWindowManager();
//                    Display d = m.getDefaultDisplay(); // 获取屏幕宽、高度
//                    WindowManager.LayoutParams p = dialogWindow.getAttributes(); // 获取对话框当前的参数值
//                    p.width = (int) (d.getWidth() * 0.7); // 宽度设置为屏幕的0.65，根据实际情况调整
//                    p.height = p.width;
//                    dialogWindow.setAttributes(p);
//                    ImageView iv_qr_code = dialog.findViewById(R.id.iv_qr_code);
//                    iv_qr_code.setImageBitmap(bitmap);
//                } else {
//                    Toast.makeText(MaintainListActivity.this, "生成二维码失败", Toast.LENGTH_SHORT).show();
//                }
//
//            }
//        }.execute();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEvent(RefreshData event) {
        refreshData();
    }


    @Override
    protected void onDestroy() {
        EventBus eb = EventBus.getDefault();
        if (eb.isRegistered(this)) {
            eb.unregister(this);
        }
        super.onDestroy();
    }

    private void getQueryLocationBean(String select) {
        ApiService.getRouteQuery(select)
                .compose(RxSchedulersHelper.io_main())
                .subscribe(new RxObserver<ResponseData<List<RouteQueryBean>>>() {
                    @Override
                    public void _onSubscribe(Disposable d) {
                        super._onSubscribe(d);
                    }

                    @Override
                    public void _onNext(ResponseData<List<RouteQueryBean>> retData) {
                        if (retData.retCode == 10000 && retData.data != null) {
                            locationList.clear();
                            companyList.clear();
                            factoryList.clear();
                            childList.clear();
                            locationList.add(new RouteQueryBean("","","全部"));
                            locationList.addAll(retData.data);
                        }
                    }

                    @Override
                    public void _onError(String errorMessage) {
                        Log.e("tou", errorMessage);
                    }

                    @Override
                    public void onComplete() {
                        super.onComplete();
                    }
                });
    }





}
